/*
 Copyright (c) 2000-2001, Neil Rhodes and Julie McKeehan
    neil@pobox.com
 All rights reserved.

From the book "Palm Programming, the Developer's Guide, 2nd edition"
by O'Reilly.

Permission granted to use this file however you see fit.
*/

#define DO_NOT_ALLOW_ACCESS_TO_INTERNALS_OF_STRUCTS
#include <BuildDefines.h>
#ifdef DEBUG_BUILD
#define ERROR_CHECK_LEVEL ERROR_CHECK_FULL
#endif
#include <PalmOS.h>
#include "ResourceDefines.h"
#include "MainForm.h"
#include "SecondForm.h"
#include "Utils.h"
#include "Constants.h"

static Boolean AppHandleEvent(EventPtr event)
{
  UInt16 formId;
  FormPtr form;

  if (event->eType == frmLoadEvent) {
    // Load the form resource.
    formId = event->data.frmLoad.formID;
    form = FrmInitForm(formId);
    ErrFatalDisplayIf(!form, "Can't initialize form");
    FrmSetActiveForm(form);

    // Set the event handler for the form.  The handler of the currently
    // active form is called by FrmHandleEvent each time is receives an
    // event.
    switch (formId) {
    case MainForm:
      FrmSetEventHandler(form, MainFormHandleEvent);
      break;

    case SecondForm:
      FrmSetEventHandler(form, SecondFormHandleEvent);
      break;

    default:
      ErrFatalDisplay("Invalid Form Load Event");
      break;

    }
    return true;
  } else 
    return false;
}


static 
void AppEventLoop(void)
{
  Err error;
  EventType event;
  do {
    EvtGetEvent(&event, evtWaitForever);
    
    if (! SysHandleEvent(&event))
      if (! MenuHandleEvent(0, &event, &error))
        if (! AppHandleEvent(&event))
          FrmDispatchEvent(&event);

  } while (event.eType != appStopEvent);
}


static 
Err AppStart(void)
{
   return errNone;
}


static 
void AppStop(void)
{
  FrmCloseAllForms();
}



UInt32 PilotMain(UInt16 launchCode, MemPtr launchParameters, 
  UInt16 launchFlags)
{
#pragma unused(launchParameters)
  Err error;

  switch (launchCode) {
  case sysAppLaunchCmdNormalLaunch:
    error = RomVersionCompatible (kOurMinVersion, launchFlags);
    if (error) 
      return error;
    error = AppStart();
    if (error) 
      return error;
      
    FrmGotoForm(MainForm);
    AppEventLoop();
    AppStop();
    break;

  default:
    break;
  }
  
  return errNone;
}


